package com.ushio.gougouwangguo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ushio.commonmodule.utils.JwtUtil;
import com.ushio.gougouwangguo.entity.mysql.SeasonEvent;
import com.ushio.gougouwangguo.entity.mysql.UserSeasonEvent;
import com.ushio.commonmodule.pojo.vo.UserSeasonEventVo;
import com.ushio.gougouwangguo.mapper.SeasonEventMapper;
import com.ushio.gougouwangguo.mapper.UserSeasonEventMapper;
import com.ushio.gougouwangguo.service.IUserSeasonEventService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张文凯
 * @since 2025-09-23
 */
@Service
public class UserSeasonEventServiceImpl extends ServiceImpl<UserSeasonEventMapper, UserSeasonEvent> implements IUserSeasonEventService {

    @Autowired
    UserSeasonEventMapper userSeasonEventMapper;

    @Autowired
    SeasonEventMapper seasonEventMapper;


    @Override
    public UserSeasonEventVo getSeasonEvent(Long userId) {
        //查询 上次 关闭页面时 是什么季节 并且 查询出 以及 这个季节的开始时间 和 事件 结束后的时间 因为 有可能 会跨季节 所以 要计算进度条
        UserSeasonEventVo userSeasonEventVo = userSeasonEventMapper.getSeasonEvent(userId);
        //查出 所有的季节
        List<SeasonEvent> seasonEvents = seasonEventMapper.selectList(new LambdaQueryWrapper<>());

        return currentSeasonAttribute(userSeasonEventVo, seasonEvents);
    }

    private UserSeasonEventVo currentSeasonAttribute(UserSeasonEventVo userSeasonEventVo, List<SeasonEvent> seasonEvents) {

        Integer seasonEventId = userSeasonEventVo.getSeasonEventId();
        LocalDateTime seasonStartTime = userSeasonEventVo.getSeasonStartTime();
        LocalDateTime seasonCurrentTime = userSeasonEventVo.getSeasonCurrentTime();

        // 已经过去了多少秒
        long seconds = Duration.between(seasonStartTime, seasonCurrentTime).getSeconds();

        // 找出当前季节
        SeasonEvent currentSeason = seasonEvents.stream()
                .filter(e -> Objects.equals(e.getSeasonEventId(), seasonEventId))
                .findFirst()
                .orElse(null);

        if (currentSeason == null) {
            return userSeasonEventVo;
        }

        int consumeTime = currentSeason.getConsumeTime();

        // 当前季节没过完
        if (seconds < consumeTime) {
            double progressPercent = ((double) seconds / consumeTime) * 100;
            progressPercent = Math.min(progressPercent, 100.0);
            double formattedProgress = Math.round(progressPercent * 100.0) / 100.0;

            userSeasonEventVo.setProgress(formattedProgress);
            userSeasonEventVo.setSeasonEventName(currentSeason.getSeasonEventName());
            return userSeasonEventVo;
        }

        // ⚡ 跨季节逻辑
        long remainingSeconds = seconds;
        int index = seasonEvents.indexOf(currentSeason);
        SeasonEvent nextSeason = currentSeason;

        // 循环减去季节时长，直到剩余秒数小于一个季节的时长
        while (remainingSeconds >= nextSeason.getConsumeTime()) {
            remainingSeconds -= nextSeason.getConsumeTime();
            index = (index + 1) % seasonEvents.size(); // 春夏秋冬循环
            nextSeason = seasonEvents.get(index);
        }

        // 计算当前季节的进度
        double progressPercent = ((double) remainingSeconds / nextSeason.getConsumeTime()) * 100;
        System.out.println("========================第一次计算=================");
        System.out.println(progressPercent);
        progressPercent = Math.min(progressPercent, 100.0);
        System.out.println("========================第二次计算===================");
        System.out.println(progressPercent);
        double formattedProgress = Math.round(progressPercent * 100.0) / 100.0;
        System.out.println("========================最终结果=================");
        System.out.println(formattedProgress);

        // 更新 userSeasonEventVo
        userSeasonEventVo.setSeasonEventId(nextSeason.getSeasonEventId());
        userSeasonEventVo.setSeasonEventName(nextSeason.getSeasonEventName());

        if (formattedProgress<0){
            throw new RuntimeException("计算出来为负数"+progressPercent);
        }

        userSeasonEventVo.setProgress(formattedProgress);

        return userSeasonEventVo;
    }


    @Override
    public void theChangeOfSeasons() {

        Long userId = JwtUtil.parseUser().getUserId();

        LocalDateTime now = LocalDateTime.now();

        UserSeasonEventVo userSeasonEventVo = userSeasonEventMapper.getSeasonEvent(userId);

        Integer seasonEventId = userSeasonEventVo.getSeasonEventId();

        UserSeasonEvent userSeasonEvent = UserSeasonEvent.builder().build();

        userSeasonEvent.setSeasonStartTime(now);

        if (seasonEventId == 1) {

            userSeasonEvent.setSeasonEventId(2);

            userSeasonEvent.setUserSeasonEventId(userSeasonEventVo.getUserSeasonEventId());

            userSeasonEventMapper.updateById(userSeasonEvent);
        } else if (seasonEventId == 2){
            userSeasonEvent.setSeasonEventId(3);

            userSeasonEvent.setUserSeasonEventId(userSeasonEventVo.getUserSeasonEventId());

            userSeasonEventMapper.updateById(userSeasonEvent);
        }if (seasonEventId == 3){
            userSeasonEvent.setSeasonEventId(4);

            userSeasonEvent.setUserSeasonEventId(userSeasonEventVo.getUserSeasonEventId());

            userSeasonEventMapper.updateById(userSeasonEvent);
        }if (seasonEventId == 4){
            userSeasonEvent.setSeasonEventId(1);

            userSeasonEvent.setUserSeasonEventId(userSeasonEventVo.getUserSeasonEventId());

            userSeasonEventMapper.updateById(userSeasonEvent);
        }
    }

    public void theChangeOfSeasons(UserSeasonEventVo userSeasonEventVo){



    }

}
